#!/usr/bin/python3
import urllib.request
import urllib.parse
import ssl
import json
import re
import hashlib
import time
import demo


def md5(str):
    # 创建md5对象
    hl = hashlib.md5()

    # Tips
    # 此处必须声明encode
    # 否则报错为：hl.update(str)    Unicode-objects must be encoded before hashing
    hl.update(str.encode(encoding='utf-8'))
    return hl.hexdigest()


def test():
  request = urllib.request.Request("http://aidemo.youdao.com/trans")
  f = urllib.request.urlopen(request)
  print(f.read().decode('utf-8'))


def getTranslate(origin, to):
  try:
    data = urllib.parse.urlencode({'q': origin, 'from': 'zh-CHS', 'to': to})
    data = data.encode('utf-8')
    request = urllib.request.Request("https://aidemo.youdao.com/trans")
    # adding charset parameter to the Content-Type header.
    request.add_header(
        "Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
    request.add_header("Host", "aidemo.youdao.com")
    request.add_header("Origin", "https://ai.youdao.com")
    request.add_header("Referer", "https://ai.youdao.com/product-fanyi.s")
    request.add_header(
        "User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36")
    context = ssl._create_unverified_context()
    f = urllib.request.urlopen(request, data, context=context)
    result = json.loads(f.read().decode('utf-8'))
    print(result['translation'][0])
    return result['translation'][0]
  except Exception as e:
    print(origin+"翻译出错 暂停10秒")
    print(result)
    time.sleep(10)
    return getTranslate(origin, to)


def newTran(origin, to):
  request = urllib.request.Request(
      "http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule")
  request.headers = {
      'Accept': 'application/json, text/javascript, */*; q=0.01',
      'Accept-Language': 'zh-CN',
      'Cache-Control': 'no-cache',
      'Connection': 'Keep-Alive',
      'Content-Length': '204',
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
      'Cookie': 'OUTFOX_SEARCH_USER_ID=-1958201970@10.168.8.76; OUTFOX_SEARCH_USER_ID_NCOO=500507281.7589852; JSESSIONID=aaaTgHrZGrr3BdPW8snsw; ___rl__test__cookies=' + str(
          int(time.time() * 1000)) + '; fanyi-ad-id=46607; fanyi-ad-closed=1',
      'Host': 'fanyi.youdao.com',
      'Origin': 'http://fanyi.youdao.com',
      'Referer': 'http://fanyi.youdao.com/',
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134',
      'X-Requested-With': 'XMLHttpRequest'
  }

  data = {
      'action': 'FY_BY_CLICKBUTTION',
      'client': 'fanyideskweb',
      'doctype': 'json',
      'from': 'zh-CHS',
      'i': origin,
      'keyfrom': 'fanyi.web',
      'salt': str(int(time.time() * 1000)),
      'smartresult': 'dict',
      'to': to,
      'typoResult': 'false',
      'version': '2.1'
  }
  data['sign'] = md5(data['client'] + data['i'] +
                     data['salt'] + "ebSeFb%=XZ%T[KZ)c(sy!")
  request.data = urllib.parse.urlencode(data).encode('utf-8')

  response = urllib.request.urlopen(request)
  print(response.read().decode('utf-8'))


f = open('iosorigin.txt', 'r')  # 读模式
line = f.readline()
all = ''
num=0
while line:
  print(line)
  zhPattern = re.compile(r'^"([\S\s]*?)"')
  match = zhPattern.findall(line)
  if len(match) != 0:
    zhPattern1 = re.compile(u'[\u4e00-\u9fa5]+')  # 查找汉字
    match1 = zhPattern1.search(match[0])
    if match1:
      print(match[0])
      num=num+1
      text = demo.huangBaidu(match[0], "cht")
      all = all+'"'+match[0]+'" = "'+text+'";'+"\r\n"
    else:
      print("本行没有汉字")
      all = all+line
  else:
    print("本行没有尖括号")
    all = all+line
  line = f.readline()
f.close()
strFile = open("ios_cht.txt", "r+")
read_data = strFile.read()
strFile.seek(0)
strFile.truncate()
strFile.write(all)
